//void, Obj This

Building this;
int last_time_unit;
//bool carth;
Sleep(rand(1000) + 500);

this = This.AsBuilding();

if (!.IsValid) return;
//pr("auto pop dziala");
//carth = false;
//if(.race==Carthage) carth = true;
while(.IsValid){
	last_time_unit = EnvReadInt(.settlement, "last_time_unit");
	
	if(EnvReadString(.settlement, "barracks_auto_train") == "yes"){
	    int max_pop;
	        
		max_pop = .settlement.max_population;
		if(EnvReadString(.settlement, "last_train_unit") != ""){
			point ptDummy; Obj objDummy;
			Barrack barrack;
			str cmd;
			
			barrack = .settlement.BestBarrack(5);
			cmd = "train"+EnvReadString(.settlement, "last_train_unit");
			if(EnvReadString(.settlement, "last_train_unit") == "EAxetrower")
				cmd = "trainEAxeTrower";
			if(EnvReadString(.settlement, "last_train_unit") == "RVelit")
				cmd = "trainMVelit";
			if(EnvReadString(.settlement, "last_train_unit") == "RPraetorian")
				cmd = "trainMPraetorian";
			//pr(cmd);
			if(barrack.IsValid){
				if(EnvReadString(.settlement, "auto_train_max") == "yes"){
					//if(.settlement.population == max_pop || carth){
					if(.settlement.population == max_pop){
						if(EnvReadString(.settlement, "last_train_unit") != ""){
							barrack.ExecCmd(cmd, ptDummy, objDummy, false);
						}
					}
				} else {
					barrack.ExecCmd(cmd, ptDummy, objDummy, false);
					
				}
				if(last_time_unit > 2000)
					Sleep(last_time_unit+1000);
				else
					Sleep(10000);
			}
		}
	}
	if(last_time_unit > 2000)
		Sleep(last_time_unit+1000);
	else
		Sleep(10000+rand(100));
}